from django.db import models
from rest_framework import serializers


class BaseModel(models.Model):
    """为模型类 补充通用字段"""
    create_time = models.DateTimeField(auto_now_add=True,
                                       verbose_name="创建数据的时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新数据的时间")

    class Meta:
        abstract = True  # 抽象  告诉django迁移的时候 不创建BaseModel表   只是用来继承的


class BaseModelSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super().to_representation(instance)
        if not (instance.create_time and instance.update_time):
            return data
        create_time, update_time = data.get('create_time'), data.get("update_time")
        # 日期对象 转为 时间戳   日期对象.timestamp()
        create_time_stamp = int(instance.create_time.timestamp() * 1000) if create_time else 0
        update_time_stamp = int(instance.update_time.timestamp() * 1000) if update_time else 0
        if not create_time_stamp and update_time_stamp:
            return data
        data.update({"create_time": create_time_stamp, "update_time": update_time_stamp})
        return data
